package com.yyk.yykywd.mvvm.ui

import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.google.gson.Gson
import com.yyk.yykywd.*
import com.yyk.yykywd.bean.BaseBean
import com.yyk.yykywd.config.HttpUrl
import com.yyk.yykywd.mvvm.adapter.AddMaterialAdapter
import com.yyk.yykywd.mvvm.base.BaseTakePhotoActivity
import com.yyk.yykywd.mvvm.entity.FollowTypeBean
import com.yyk.yykywd.mvvm.entity.UploadBean
import com.yyk.yykywd.mvvm.event.FinishWorkDetail
import com.yyk.yykywd.mvvm.view_model.AddPictureViewModel
import com.yyk.yykywd.util.DensityUtils
import com.yyk.yykywd.util.GlideUtils
import com.yyk.yykywd.util.ToastUtil
import com.yyk.yykywd.widght.SpaceItemDecoration
import kotlinx.android.synthetic.main.activity_upload_contract.*
import kotlinx.android.synthetic.main.rl_bottom.*
import org.devio.takephoto.model.TResult
import org.greenrobot.eventbus.EventBus

class UploadContractActivity : BaseTakePhotoActivity() {
    private lateinit var viewModel: AddPictureViewModel
    private lateinit var contract_imgs_adapter: AddMaterialAdapter
    private lateinit var survey_form_adapter: AddMaterialAdapter
    private lateinit var permit_adapter: AddMaterialAdapter
    private lateinit var agent_license_adapter: AddMaterialAdapter

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            val result = msg.obj as String
            val gson = Gson()
            val info: UploadBean = gson.fromJson(result, UploadBean::class.java)
            if (info.code != 1) {
                ToastUtil.showShort(mActivity, info.msg)
                return
            }

            when (viewModel.type) {
                FROM_CONTRACT_IMG -> {
                    viewModel.contract_imgs.add(info.data)
                    contract_imgs_adapter.notifyDataSetChanged()
                }
                FROM_SURVEY_FORM -> {
                    viewModel.survey_form_imgs.add(info.data)
                    survey_form_adapter.notifyDataSetChanged()
                }
                FROM_PERMIT -> {
                    viewModel.permit_imgs.add(info.data)
                    permit_adapter.notifyDataSetChanged()
                }
                FROM_AGENT_LICENSE -> {
                    viewModel.agent_license_imgs.add(info.data)
                    agent_license_adapter.notifyDataSetChanged()
                }
                FROM_CARD -> {
                    if (viewModel.isFront) {
                        viewModel.card_front_imgs = info.data
                        GlideUtils.loadRoundCircleImage(mActivity, HttpUrl.BASE_URL + viewModel.card_front_imgs, iv_front_card, 4)
                        iv_remove1.visibility = View.VISIBLE
                    } else {
                        viewModel.card_back_imgs = info.data
                        GlideUtils.loadRoundCircleImage(mActivity, HttpUrl.BASE_URL + viewModel.card_back_imgs, iv_back_card, 4)
                        iv_remove2.visibility = View.VISIBLE
                    }
                }
            }
        }
    }

    companion object {
        const val CONTRACT_MAX_IMAGES = 10
        const val MAX_IMAGES = 3
    }

    override fun initData() {
        viewModel.getType()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_upload_contract
    }

    override fun initView() {
        setBackArrow()
        setBackArrow {
            backAndDelImg()
        }

        viewModel = getViewModel(this, AddPictureViewModel::class.java)
        viewModel.from = intent.getStringExtra(TYPE)
        viewModel.id = intent.getStringExtra(ID)

        if (viewModel.from == FROM_AGENT_PERSONAL_ADD
                || viewModel.from == FROM_AGENT_COMPANY_ADD) {
            setTitle("添加代理站点")
        } else {
            setTitle("上传合同")
        }

        rv_contract_img.layoutManager = GridLayoutManager(mActivity, 4)
        rv_survey_form.layoutManager = GridLayoutManager(mActivity, 4)
        rv_permit.layoutManager = GridLayoutManager(mActivity, 4)
        rv_agent_license.layoutManager = GridLayoutManager(mActivity, 4)
        rv_contract_img.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        rv_survey_form.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        rv_permit.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        rv_agent_license.addItemDecoration(SpaceItemDecoration(DensityUtils.dp2px(mActivity, 10f)))
        contract_imgs_adapter = AddMaterialAdapter(mActivity, viewModel.contract_imgs)
        contract_imgs_adapter.maxImages = CONTRACT_MAX_IMAGES
        rv_contract_img.adapter = contract_imgs_adapter

        survey_form_adapter = AddMaterialAdapter(mActivity, viewModel.survey_form_imgs)
        survey_form_adapter.maxImages = MAX_IMAGES
        rv_survey_form.adapter = survey_form_adapter

        permit_adapter = AddMaterialAdapter(mActivity, viewModel.permit_imgs)
        permit_adapter.maxImages = MAX_IMAGES
        rv_permit.adapter = permit_adapter

        agent_license_adapter = AddMaterialAdapter(mActivity, viewModel.agent_license_imgs)
        agent_license_adapter.maxImages = MAX_IMAGES
        rv_agent_license.adapter = agent_license_adapter

        when (viewModel.from) {
            FROM_HOSPITAL_UPLOAD -> {
                cl_upload_contract.visibility = View.GONE
                cl_proxy_site_name.visibility = View.GONE
                cl_contract_hospital.visibility = View.VISIBLE
                cl_agent_card.visibility = View.GONE
            }
            FROM_AGENT_PERSONAL_UPLOAD -> {
                cl_upload_contract.visibility = View.VISIBLE
                cl_proxy_site_name.visibility = View.VISIBLE
                cl_contract_hospital.visibility = View.GONE
                cl_agent_card.visibility = View.VISIBLE

                tv_agent_license.visibility = View.GONE
                tv_agent_license_lint.visibility = View.GONE
                rv_agent_license.visibility = View.GONE
                tv_card.text = "代理商身份证照片"
            }
            FROM_AGENT_PERSONAL_ADD,
            FROM_AGENT_COMPANY_ADD -> {
                cl_upload_contract.visibility = View.VISIBLE
                cl_proxy_site_name.visibility = View.VISIBLE
                cl_contract_hospital.visibility = View.GONE
                cl_agent_card.visibility = View.GONE
            }
            FROM_AGENT_COMPANY_UPLOAD -> {
                cl_upload_contract.visibility = View.VISIBLE
                cl_proxy_site_name.visibility = View.VISIBLE
                cl_contract_hospital.visibility = View.GONE
                cl_agent_card.visibility = View.VISIBLE

                tv_agent_license.visibility = View.VISIBLE
                tv_agent_license_lint.visibility = View.VISIBLE
                rv_agent_license.visibility = View.VISIBLE
                tv_card.text = "法人身份证照片"
            }
        }
    }

    override fun setListener() {
        super.setListener()
        setAdapterChildClickListener(mActivity, contract_imgs_adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {
                viewModel.type = FROM_CONTRACT_IMG
            }

            override fun clickRemove(position: Int) {
                viewModel.del_type = FROM_CONTRACT_IMG
                viewModel.del_position = position
                viewModel.removeImg(viewModel.contract_imgs[position])
            }

        })
        setAdapterChildClickListener(mActivity, survey_form_adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {
                viewModel.type = FROM_SURVEY_FORM
            }

            override fun clickRemove(position: Int) {
                viewModel.del_type = FROM_SURVEY_FORM
                viewModel.del_position = position
                viewModel.removeImg(viewModel.survey_form_imgs[position])
            }

        })
        setAdapterChildClickListener(mActivity, permit_adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {
                viewModel.type = FROM_PERMIT
            }

            override fun clickRemove(position: Int) {
                viewModel.del_type = FROM_PERMIT
                viewModel.del_position = position
                viewModel.removeImg(viewModel.permit_imgs[position])
            }

        })

        setAdapterChildClickListener(mActivity, agent_license_adapter,
                getTakePhoto(),
                1, object : UploadClickListener {
            override fun clickIv() {
                viewModel.type = FROM_AGENT_LICENSE
            }

            override fun clickRemove(position: Int) {
                viewModel.del_type = FROM_AGENT_LICENSE
                viewModel.del_position = position
                viewModel.removeImg(viewModel.agent_license_imgs[position])
            }

        })

        iv_front_card.setOnClickListener {
            viewModel.isFront = true
            viewModel.type = FROM_CARD
            showTakePhotoWithLimit(mActivity, getTakePhoto(), 1)
        }

        iv_back_card.setOnClickListener {
            viewModel.isFront = false
            viewModel.type = FROM_CARD
            showTakePhotoWithLimit(mActivity, getTakePhoto(), 1)
        }

        tv_execute.setOnClickListener {
            if (required()) {
                return@setOnClickListener
            }
            var msg = ""
            var title = ""
            if (viewModel.from == FROM_AGENT_PERSONAL_ADD
                    || viewModel.from == FROM_AGENT_COMPANY_ADD) {
                title = "是否确认添加站点？"
                msg = "添加站点后，将在\"工作——签订合同\"中跟进此客户"
            } else {
                title = "是否确认上传合同？"
                if (viewModel.from == FROM_HOSPITAL_UPLOAD) {
                    msg = "上传合同后将在\"工作——签订合同\"中跟进设备安装信息"
                } else {
                    msg = "上传合同后将在\"工作——签订合同\"中跟进回款信息"
                }
            }
            show(mActivity, title,
                    msg,
                    "确认",
                    "取消") {
                viewModel.uploadContract(
                        order_code = getTextString(et_contract_num),
                        handsel_price = getTextString(tv_deposit),
                        agency_name = getTextString(et_proxy_site))
            }
        }

        viewModel.delSuccess.observe(this, Observer<BaseBean> {
            if (it.code != 200) {
                ToastUtil.showShort(it.msg)
                return@Observer
            }
            if (viewModel.delSingleOrMulti == MULTI) {
                finish()
                return@Observer
            }
            when (viewModel.del_type) {
                FROM_CONTRACT_IMG -> {
                    viewModel.contract_imgs.removeAt(viewModel.del_position)
                    contract_imgs_adapter.notifyDataSetChanged()
                }
                FROM_SURVEY_FORM -> {
                    viewModel.survey_form_imgs.removeAt(viewModel.del_position)
                    survey_form_adapter.notifyDataSetChanged()
                }
                FROM_PERMIT -> {
                    viewModel.permit_imgs.removeAt(viewModel.del_position)
                    permit_adapter.notifyDataSetChanged()
                }
                FROM_AGENT_LICENSE -> {
                    viewModel.agent_license_imgs.removeAt(viewModel.del_position)
                    agent_license_adapter.notifyDataSetChanged()
                }
                FROM_CARD -> {
                    if (viewModel.isFront) {
                        viewModel.card_front_imgs = ""
                        iv_remove1.visibility = View.GONE
                        iv_front_card.setImageResource(R.drawable.pic_sfzsc)
                    } else {
                        viewModel.card_back_imgs = ""
                        iv_remove2.visibility = View.GONE
                        iv_back_card.setImageResource(R.drawable.pic_sfzsc)
                    }
                }
            }
        })

        viewModel.responseMessage.observe(this, Observer<String> { t ->
            val msg = Message.obtain()
            msg.what = 1
            msg.obj = t
            handler.sendMessage(msg)
        })

        viewModel.uploadSuccess.observe(this, Observer<BaseBean> {
            ToastUtil.showShort(it.msg)
            if (it.code == 200) {
                EventBus.getDefault().post(FinishWorkDetail())
                finish()
            }
        })

        tv_site_type.setOnClickListener {
            if (viewModel.siteType.isEmpty()) {
                return@setOnClickListener
            }
            val list = viewModel.siteType.map { it.name }
            val showOptionsPicker = showOptionsPicker(mActivity) { options1: Int, _: Int, _: Int ->
                viewModel.sitePosition = options1
                tv_site_type.text = list[options1]
                tv_agent_price.text = viewModel.siteType[options1].id + "元"
            }
            showOptionsPicker.setSelectOptions(0, 0, 0)
            showOptionsPicker.setPicker(list) //三级选择器
            showOptionsPicker.show()
        }

        tv_contract_type.setOnClickListener {
            if (viewModel.contractType.isEmpty()) {
                return@setOnClickListener
            }
            val list = viewModel.contractType.map { it.name }
            val showOptionsPicker = showOptionsPicker(mActivity) { options1: Int, _: Int, _: Int ->
                tv_contract_type.text = list[options1]
                viewModel.contractTypePosition = options1
                if (list[options1] == "全款合同") {
                    cl_deposit_amount.visibility = View.GONE
                    tv_deposit.setText("")
                } else {
                    cl_deposit_amount.visibility = View.VISIBLE
                }
            }
            showOptionsPicker.setSelectOptions(0, 0, 0)
            showOptionsPicker.setPicker(list) //三级选择器
            showOptionsPicker.show()
        }

        iv_remove1.setOnClickListener {
            viewModel.del_type = FROM_CARD
            viewModel.removeImg(viewModel.card_front_imgs)
        }
        iv_remove2.setOnClickListener {
            viewModel.del_type = FROM_CARD
            viewModel.removeImg(viewModel.card_back_imgs)
        }
    }

    override fun takeSuccess(result: TResult) {
        viewModel.uploadContractImg(CONTRACT, result.image.compressPath)
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAndDelImg()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun backAndDelImg() {
        with(viewModel) {
            val list = contract_imgs + survey_form_imgs + permit_imgs + agent_license_imgs
            val list1 = list as MutableList<String>
            if (card_front_imgs.isNotEmpty()) {
                list1.add(card_front_imgs)
            }
            if (card_back_imgs.isNotEmpty()) {
                list1.add(card_back_imgs)
            }
            if (list1.isNotEmpty()) {
                delSingleOrMulti = MULTI
                removeImg(listToString(list1))
            } else {
                finish()
            }
        }
    }

    private fun required(): Boolean {
        val siteType = getTextString(tv_site_type)
        val contractNum = getTextString(et_contract_num)
        val contractType = getTextString(tv_contract_type)
        val deposit = getTextString(tv_deposit)
        with(viewModel) {
            if (siteType == "请选择") {
                ToastUtil.showShort("请选择站点类型")
                return true
            }
            if (contractNum.isEmpty()) {
                ToastUtil.showShort("请填写合同编号")
                return true
            }
            if (contract_imgs.isEmpty()) {
                ToastUtil.showShort("请上传合同图片")
                return true
            }
            when (from) {
                FROM_HOSPITAL_UPLOAD -> {
                    if (survey_form_imgs.isEmpty()) {
                        ToastUtil.showShort("请上传医院施工调研表")
                        return true
                    }
                }
                FROM_AGENT_PERSONAL_UPLOAD ->{
                    if (getTextString(et_proxy_site).isEmpty()) {
                        ToastUtil.showShort("请填写代理站点名称")
                        return true
                    }
                    if (contractType == "请选择") {
                        ToastUtil.showShort("请选择合同类型")
                        return true
                    }
                    if (contractType == "定金合同" && deposit.isEmpty()) {
                        ToastUtil.showShort("请填写定金金额")
                        return true
                    }
                    if (contractType == "定金合同") {
                        val s = tv_agent_price.text.toString()
                        val agentPrice = cutOneCharacter(s).toInt()
                        val depositNum = deposit.toInt()
                        if (depositNum == 0) {
                            ToastUtil.showShort("定金金额不能为0")
                            return true
                        }
                        if (depositNum > agentPrice) {
                            ToastUtil.showShort("定金金额不能大于代理价格")
                            return true
                        }
                    }
                    if (card_front_imgs.isEmpty()) {
                        ToastUtil.showShort("请上传代理商身份证照片正面")
                        return true
                    }
                    if (card_back_imgs.isEmpty()) {
                        ToastUtil.showShort("请上传代理商身份证照片背面")
                        return true
                    }
                }
                FROM_AGENT_COMPANY_UPLOAD -> {
                    if (getTextString(et_proxy_site).isEmpty()) {
                        ToastUtil.showShort("请填写代理站点名称")
                        return true
                    }
                    if (contractType == "请选择") {
                        ToastUtil.showShort("请选择合同类型")
                        return true
                    }
                    if (contractType == "定金合同" && deposit.isEmpty()) {
                        ToastUtil.showShort("请填写定金金额")
                        return true
                    }

                    if (contractType == "定金合同") {
                        val s = tv_agent_price.text.toString()
                        val agentPrice = cutOneCharacter(s).toInt()
                        val depositNum = deposit.toInt()
                        if (depositNum == 0) {
                            ToastUtil.showShort("定金金额不能为0")
                            return true
                        }
                        if (depositNum > agentPrice) {
                            ToastUtil.showShort("定金金额不能大于代理价格")
                            return true
                        }
                    }

                    if (agent_license_imgs.isEmpty()) {
                        ToastUtil.showShort("请上传代理商企业营业执照")
                        return true
                    }

                    if (card_front_imgs.isEmpty()) {
                        ToastUtil.showShort("请上传法人身份证照片正面")
                        return true
                    }
                    if (card_back_imgs.isEmpty()) {
                        ToastUtil.showShort("请上传法人身份证照片正面")
                        return true
                    }
                }
                FROM_AGENT_PERSONAL_ADD,
                FROM_AGENT_COMPANY_ADD -> {
                    if (getTextString(et_proxy_site).isEmpty()) {
                        ToastUtil.showShort("请填写代理站点名称")
                        return true
                    }
                    if (contractType == "请选择") {
                        ToastUtil.showShort("请选择合同类型")
                        return true
                    }
                    if (contractType == "定金合同" && deposit.isEmpty()) {
                        ToastUtil.showShort("请填写定金金额")
                        return true
                    }

                    if (contractType == "定金合同") {
                        val s = tv_agent_price.text.toString()
                        val agentPrice = cutOneCharacter(s).toInt()
                        val depositNum = deposit.toInt()
                        if (depositNum == 0) {
                            ToastUtil.showShort("定金金额不能为0")
                            return true
                        }
                        if (depositNum > agentPrice) {
                            ToastUtil.showShort("定金金额不能大于代理价格")
                            return true
                        }
                    }
                }
            }
            return false
        }
    }
}
